package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Service
@RabbitListener(queues = "order.dead.queue")    //监听订单的死信队列
public class OrderCloseListener {
    @Autowired OrderService orderService;
    /**
     * 消费者监听消息, 要有消费者才能创建出交换机和队列
     */
    @RabbitHandler
    public void handle(OrderEntity entity, Channel channel, Message message) throws IOException {
        System.out.println("接收到过期的订单消息, 准备关闭订单，订单号：" + entity.getOrderSn() + " => " + entity.getId());
        try{
            orderService.closeOrder(entity);    //调用《关闭订单》方法
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);  //true：消费失败，则重新入队
        }}}
